<template>
  <div class="dashboard">
    <h1 style="text-align: center;">新生报到人数看板</h1>

    <div>
      <!-- 饼图 -->
      <div class="pieChart chart_div" ref="pieChart" style="width: 600px; height: 400px; margin-bottom: 20px;"></div>
      <!-- 柱状图 -->
      <div class="barChart chart_div" ref="barChart" style="width: 600px; height: 400px;"></div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue';
import {countStudentGrade} from '@/api/system/user';

function loadScript(src, callback) {
  const script = document.createElement('script');
  script.src = src;
  script.onload = callback;
  document.head.appendChild(script);
}

const pieChart = ref(null);
const barChart = ref(null);
const myPieChart = ref(null);
const myBarChart = ref(null);

const chartData = {studentGrade: '2024'};

function updateCharts() {
  countStudentGrade(chartData)
      .then(response => {
        const result = response;

        const totalStudents = result.reduce((sum, student) => sum + (student.ying || 0), 0);
        const totalStudentsReported = result.reduce((sum, student) => sum + (student.shi || 0), 0);

        const data = {
          totalStudents: totalStudents,
          colleges: [
            {name: '体艺学院', reportedStudents: result[0]?.shi || 0, totalStudents: result[0]?.ying || 0},
            {name: '大信学院', reportedStudents: result[1]?.shi || 0, totalStudents: result[1]?.ying || 0},
            {name: '建工学院', reportedStudents: result[2]?.shi || 0, totalStudents: result[2]?.ying || 0},
            {name: '文传学院', reportedStudents: result[3]?.shi || 0, totalStudents: result[3]?.ying || 0},
            {name: '经管学院', reportedStudents: result[4]?.shi || 0, totalStudents: result[4]?.ying || 0},
            {name: '文旅学院', reportedStudents: result[5]?.shi || 0, totalStudents: result[5]?.ying || 0},
            {name: '法学院', reportedStudents: result[6]?.shi || 0, totalStudents: result[6]?.ying || 0},
          ]
        };

        // 更新饼图
        const pieOptions = {
          title: {
            text: '全校新生报到人数',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: params => {
              return `${params.data.name}: ${params.data.value}人 (${params.percent}%)`;
            }
          },
          legend: {
            orient: 'vertical',
            left: '10px',
            top: '20px',
          },
          series: [
            {
              name: '人数比例',
              type: 'pie',
              radius: '50%',
              data: [
                {value: totalStudentsReported, name: '已报到人数'},
                {value: totalStudents - totalStudentsReported, name: '未报到人数'}
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                show: true,
                formatter: '{b}: {c}人',
                position: 'outside'
              }
            }
          ],
          graphic: {
            type: 'text',
            left: 'center',
            top: '85%',
            style: {
              text: `全校应报到人数：${totalStudents}人          已报到人数：${totalStudentsReported}人`,
              textAlign: 'center',
              fontSize: 16,
              fontWeight: 'bold'
            }
          }
        };
        myPieChart.value.setOption(pieOptions);

        // 更新柱状图
        const barOptions = {
          title: {
            text: '各学院已报到人数与总报到人数',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {type: 'shadow'}
          },
          legend: {
            data: ['已报到人数', '总人数'],
            top: 30
          },
          xAxis: {
            type: 'category',
            data: data.colleges.map(college => college.name)
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '已报到人数',
              type: 'bar',
              data: data.colleges.map(college => college.reportedStudents),
              itemStyle: {color: '#73C9E6'},
              label: {
                show: true,
                position: 'top',
                formatter: '{c}'
              }
            },
            {
              name: '总人数',
              type: 'bar',
              data: data.colleges.map(college => college.totalStudents),
              itemStyle: {color: '#5470C6'},
              label: {
                show: true,
                position: 'top',
                formatter: '{c}'
              },
              barCategoryGap: '10%',
              barGap: '0%'
            }
          ]
        };
        myBarChart.value.setOption(barOptions);
      })
      .catch(error => {
        console.error('Error:', error);
      });
}

onMounted(() => {
  loadScript('/echarts.min.js', () => {
    // 初始化图表实例
    myPieChart.value = echarts.init(pieChart.value);
    myBarChart.value = echarts.init(barChart.value);

    // 首次加载数据并绘制图表
    updateCharts();

    // 每隔一分钟更新一次数据
    const intervalId = setInterval(updateCharts, 60000);

    // 清理定时器
    onUnmounted(() => {
      clearInterval(intervalId);
    });
  });
});
</script>

<style scoped>
h1 {
  margin: 50px 0;
}

.chart_div {
  display: inline-block;
  margin: 0 20px;
}
</style>
